package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author : sunjun
 * @email : sunjun0207@163.com
 * @create 2019/11/16 19:31
 */
//后台系统-->图形报表展示
@RestController
@RequestMapping("/report")
public class ReportController {
    //使用dubbo通过远程调用服务
    @Reference
    private MemberService memberService;//去注册中心订阅userService服务
    //注入setmealService,使用dubbo远程调用服务
    @Reference
    private SetmealService setmealService;
    //注入reportService,使用dubbo远程调用服务
    @Reference
    private ReportService reportService;


    /*
    后台管理-->导出Excel报表
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        //程序健壮性和安全性处理
        try {
            //远程调用报表服务获取报表数据
            Map<String,Object> result = reportService.getBusinessReport();
            //取出返回结果数据,将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //获取Excel模板文件绝对路径
            //File.separator:适应在不同系统下,文件的路径Windows:\,Linux:/
            String templateRealPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //读取模板文件创建表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            //获取Excel中的工作簿
            XSSFSheet sheet = workbook.getSheetAt(0);
            //获取工作簿中的行
            XSSFRow row = sheet.getRow(2);
            //获取指定单元格内容
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//今天新增会员数
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
            return null;
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    /*
    后台管理-->获取运营统计数据
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        //程序健壮性和安全性处理
        try {
            //调用reportService完成查询
            Map<String,Object> result =  reportService.getBusinessReport();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }



    /*
    后台管理-->套餐预约占比(饼形图)
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        //程序健壮性和安全性处理
        try {
            //调用setmealService完成套餐数量查询,
            List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();
            //将查询套餐setmealCount集合封装到map集合
            Map<String,Object> map = new HashMap<>();
            map.put("setmealCount",setmealCount);
            //获取套餐名称,封装到setmealNames套餐名集合中
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> m : setmealCount) {
                String name = (String) m.get("name");
                setmealNames.add(name);
            }
            //将套餐名称封装到map集合
            map.put("setmealNames",setmealNames);
            //返回结果到前台
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }



    /*
    后台管理-->会员数量统计(折线图)
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
/*
        //模拟数据测试对象格式转为echarts所需的数据格式
        Map<String,Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();
        months.add("2018.05");
        months.add("2018.06");
        months.add("2018.07");
        months.add("2018.08");
        months.add("2018.09");
        map.put("months",months);

        List<Integer> memberCount = new ArrayList<>();
        memberCount.add(200);
        memberCount.add(300);
        memberCount.add(400);
        memberCount.add(500);
        memberCount.add(600);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
*/
        //创建日历对象
        Calendar calendar = Calendar.getInstance();
        //获取当前日期之--前12个月的日期
        calendar.add(Calendar.MONTH,-12);
        //存放months:2018-05
        List<String> months = new ArrayList<>();
        for (int i = 0; i < 12; i++) {//取出当前月前12个月
            calendar.add(Calendar.MONTH,1);
            months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
        }
        //存放月份:2018.05
        Map<String,Object> map = new HashMap<>();
        map.put("months",months);
        //程序健壮性和安全性处理
        try {
            //存放会员数量memberCount
            List<Integer> memberCount = memberService.findMemberCountByMonth(months);
            map.put("memberCount",memberCount);
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

}
